const router =require('express').Router();
const bodyParser=require('body-parser');
const crypto=require('crypto');
const USER=require('../mock/user.js');
const AES_conf = {
    key: 'betasoft.cn.saas', //密钥
    iv: 'betasoft.cn.saas', //偏移向量
    padding: 'PKCS5Padding' //补全值
};

router.put('/signin',(req,res)=>{
    let {name,password}=req.body;
    password=decryption(password);
    password=crypto.createHash('md5').update(password).digest('hex');

    if(name!=USER.name || password!==USER.password)return res.send({
        code:-1,
        msg:'用户名或密码错误'
    });


    res.send({
        code:0,
        msg:'',
        data:{    
            uid:USER.uid,
            name:USER.name,
            access_token:USER.access_token,
            refresh_token:USER.refresh_token,
            expires_in:USER.expires_in
        }
    });
});

router.put('/signout',(req,res)=>{
    res.send({
        code:0,
        msg:'登出成功'
    });
});


router.put('/info',(req,res)=>{
    let token=req.header('Authorization');
    console.log('Authorization:',req.header('Authorization'));
    console.log('body:',req.body);

    if(token !== 'Bearer '+USER.access_token)return res.send({
        code:1,
        msg:'access_token过期'
    });

    res.send({
    	code:0,
		msg:'',
    	data:{    
            uid:USER.uid,
    		name:USER.name,
    		email:USER.email,
            avatar:USER.avatar,
            status:USER.status
    	}
    });
});

module.exports=router;


function decryption(data){
    let key = AES_conf.key;
    let iv = AES_conf.iv;
    // let padding = AES_conf.padding;

    var cipherChunks = [];
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    decipher.setAutoPadding(true);
    cipherChunks.push(decipher.update(data, 'base64', 'utf8'));
    cipherChunks.push(decipher.final('utf8'));
    return cipherChunks.join('');
}